package cn.com.dealme.domain.repository.impl;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;
import org.zzm.util.PageHelper;

import cn.com.dealme.domain.model.Commodity;
import cn.com.dealme.domain.persistence.CatagoryPersistenceProxy;
import cn.com.dealme.domain.persistence.CommodityPersistenceProxy;
import cn.com.dealme.domain.repository.ICommodityRepository;

public class CommodityRepositoryImpl implements ICommodityRepository {

	private static final int pageSize = 20;

	private Session session;

	public void delete(Long id) {
		session.delete(session.get(CommodityPersistenceProxy.class, id));
	}

	public void delete(Long[] ids) {
		for (Long id : ids) {
			session.delete(session.get(CommodityPersistenceProxy.class, id));
		}
	}

	public Commodity find(Long id) {
		return (Commodity) session.get(CommodityPersistenceProxy.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<Commodity> queryByPage(int page, int size) {
		String entityName = session.getSessionFactory().getClassMetadata(
				CatagoryPersistenceProxy.class).getEntityName();
		
		return session.createQuery("from " + entityName).setFirstResult(
				PageHelper.getFirstResult(page, pageSize)).setMaxResults(
						pageSize).list();
	}

	@SuppressWarnings("unchecked")
	public List<Commodity> queryLike(Map<String, Object> likes, int page,
			int size) {
		Criteria dc = session.createCriteria(CatagoryPersistenceProxy.class);
		dc.setFirstResult(PageHelper.getFirstResult(page, pageSize));
		dc.setMaxResults(pageSize);
		Disjunction dj = Restrictions.disjunction();
		for(Entry<String, Object> entry : likes.entrySet()) {
			dj.add(Restrictions.like(entry.getKey(), entry.getValue()));
		}
		dc.add(dj);
		return dc.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Commodity> queryAllEq(Map<String, Object> eqs, int page,
			int size) {
		Criteria dc = session.createCriteria(CatagoryPersistenceProxy.class);
		dc.setFirstResult(PageHelper.getFirstResult(page, pageSize));
		dc.setMaxResults(pageSize);
		Conjunction cj = Restrictions.conjunction();
		for(Entry<String, Object> entry : eqs.entrySet()) {
			cj.add(Restrictions.like(entry.getKey(), entry.getValue()));
		}
		dc.add(cj);
		return dc.list();
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	

}
